<?php
/**
 * Created by PhpStorm.
 * User: reshared
 * Date: 2017/9/28
 * Time: 下午1:46
 */

namespace Index\Repository;


use Index\Repository\Tra\InstanceTrait;

class UserRepository extends BaseRepository
{
    use InstanceTrait;

    /**
     * 尝试登录,或者验证身份不登录
     * @param $username
     * @param $password
     * @param bool $login
     * @return bool
     */
    public function attempt($username, $password, $login = true)
    {
        //判断登录方式
        if (isMobile($username)){
            $user = $this->model('user')->getByMobile($username);
        } else {
            $user = $this->model('user')->getByUsername($username);
        }
        if (!$user) {
            return false;
        }
        //判定
        if (!$this->model('user')->validatePassword($user, $password)) {
            return false;
        }
        //是否需要登录
        if (!$login) {
            return true;
        }
        //执行登录
        $this->loginByUser($user);
        return true;
    }

    /**
     * 判断是否已经登录
     * @return bool
     */
    public function hasLogin()
    {
        return session_has('user');
    }

    /**
     * 获取用户信息,参数则为某个信息的字段
     * @param string $key
     * @return bool|mixed
     */
    public function user($key = '')
    {
        //获取用户信息
        $user = session_get('user');
        //若无字段,返回全部
        if (!$key) {
            return $user;
        }
        //返回字段对应值
        return $user ? $user[$key] : false;
    }

    /**
     * 设置用户登录
     * @param $user
     */
    public function setLogin($user)
    {
        session_set('user', $user);
    }

    /**
     * 用户登出
     */
    public function setLogout()
    {
        session_clear('user');
    }

    /**
     * 设置用户登录 by user_id
     * @param $uid
     */
    public function setLoginByUid($uid)
    {
        $this->setLogin($this->model('user')->getById($uid));
    }

    /**
     * 获取用户 by username or mobile
     * @param $username
     * @return mixed
     */
    public function getByUser($username)
    {
        if (isMobile($username)){
            return $this->model('user')->getByMobile($username);
        }

        return $this->model('user')->getByUsername($username);
    }

    /**
     * 获取用户 by user_id
     * @param $user
     * @return bool
     */
    public function loginByUser($user)
    {
        //设置session
        $this->setLogin($user);
        //记录登录
        $this->event('user')->login($user['user_id']);
    }

    /**
     * 重置密码方法
     * @param $uid
     * @param $password
     * @return mixed
     */
    public function resetPassword($uid, $password)
    {
        $salt = randToken(2);

        return $this->model('user')->updateUser($uid, array(
            'password'  => $this->model('user')->encodePassword($password, $salt),
            'salt'      => $salt,
            'last_time' => time()
            ));
    }
}